﻿using UnityEngine;
using System.Collections;
using MacGruber;
using System.Linq;
using System.Collections.Generic;
using System.Text;
using MVR.FileManagementSecure;
using System;
using Object = UnityEngine.Object;

public class DebugTool : MVRScript
{
    private JSONStorableStringChooser searchStringStorableChooser;
    private JSONStorableString strInputStorableString;
    private JSONStorableBool testB;
    Transform camtarget;
    Transform targetAtom;

    public override void Init()
    {
        Utils.OnInitUI(CreateUIElement);

        //testB = Utils.SetupToggle(this, "fdfdf", true, false);
        //testB.setCallbackFunction = (bb) => {
        //    SuperController.singleton.MonitorCenterCamera.enabled = bb;
        //};

        //camtarget = SuperController.singleton.centerCameraTarget.transform;
        camtarget = SuperController.singleton.MonitorCenterCamera.transform;

        string logStr = "";

        Utils.SetupButton(this, "打印所有控制体", () => {
            SuperController.singleton.ClearMessages();
            var controllerList = GetAllControllers();
            logStr = "";
            for (int i = 0; i < controllerList.Length; i++)
            {
                logStr += controllerList[i].name + "\n";
            }
            SuperController.LogMessage(logStr);
        }, false);

        Utils.SetupButton(this, "打印所有原子", () => {
            SuperController.singleton.ClearMessages();
            var atomList = GetAtomUIDs();
            logStr = "";
            for (int i = 0; i < atomList.Count; i++)
            {
                logStr += atomList[i] + "\n";
            }
            SuperController.LogMessage(logStr);
        }, false);

        Utils.SetupButton(this, "打开文件面板", () => {
            ShowTexturePicker();
        }, false);

        Utils.SetupSpacer(this, 10, false);

        Utils.SetupButton(this, "打印当前所选物体的层次结构(简要)", () => {
            var atom = SuperController.singleton.GetSelectedAtom();
            if (atom == null) return;
            SuperController.singleton.ClearMessages();
            Utils.LogTransform(string.Format("{0}原子的结构", atom.name), atom.transform);
        }, false);

        Utils.SetupButton(this, "打印当前所选物体的层次结构(详细)", () => {
            var atom = SuperController.singleton.GetSelectedAtom();
            if (atom == null) return;
            SuperController.singleton.ClearMessages();
            Utils.LogTransform(string.Format("{0}原子的结构", atom.name), atom.transform,false);
        }, false);

        //搜索指定类型，指定名称的物体，打印出路径
        searchStringStorableChooser = Utils.SetupStringChooser(this, "搜索类型", new List<string>() { "ComponentType", "ObjectName" }, 0, false);
        strInputStorableString = new JSONStorableString("输入", "");
        Utils.SetupTextInput(this, "输入：", strInputStorableString, false);
        Utils.SetupButton(this, "打印搜索到的物体完整层次", () => {

            SuperController.singleton.ClearMessages();

            if (searchStringStorableChooser.val == "ComponentType")
            {
                System.Type type = System.Type.GetType(strInputStorableString.val);
                SuperController.LogMessage(type.ToString());
                Object[] objects = Resources.FindObjectsOfTypeAll(type);
                
                
                if (objects.Length > 0)
                {
                    SuperController.LogMessage(objects[0].name);
                    for (int i = 0; i < objects.Length; i++)
                    {
                        StringBuilder stringBuilder = new StringBuilder();
                        Utils.GetObjectScenePath((objects[i] as GameObject).transform, stringBuilder);
                        SuperController.LogMessage(stringBuilder.ToString());
                    }
                }
            }
            else if (searchStringStorableChooser.val == "ObjectName")
            {
                GameObject[] objects = Resources.FindObjectsOfTypeAll<GameObject>();
                SuperController.LogMessage(objects.Length.ToString());
                if (objects.Length > 0)
                {
                    for (int i = 0; i < objects.Length; i++)
                    {
                        if (objects[i].name.Contains(strInputStorableString.val))
                        {
                            StringBuilder stringBuilder = new StringBuilder();
                            Utils.GetObjectScenePath(objects[i].transform, stringBuilder);
                            SuperController.LogMessage(stringBuilder.ToString());
                        }
                    }
                }
            }
            try
            {
                
            }
            catch (System.Exception e)
            {
                SuperController.LogError(e.Message);
                throw;
            }
            
        }, false);

    }

    private void Update()
    {

        targetAtom = SuperController.singleton.GetSelectedController().transform;
        if (targetAtom != null)
        {
            if (Input.GetKeyDown(KeyCode.Keypad4))
            {
                Vector3 pos = targetAtom.position + targetAtom.right * -1;
                camtarget.position = pos;
                camtarget.LookAt(targetAtom, Vector3.up);
                SuperController.singleton.centerCameraTarget.targetCamera.transform.LookAt(targetAtom, Vector3.up);
            }
            else if (Input.GetKeyDown(KeyCode.Keypad1))
            {
                Vector3 pos = targetAtom.position + Vector3.down * 1;
                camtarget.position = pos;
                camtarget.LookAt(targetAtom, Vector3.up);
                SuperController.singleton.centerCameraTarget.targetCamera.transform.LookAt(targetAtom, Vector3.up);
            }
            else if (Input.GetKeyDown(KeyCode.Keypad3))
            {
                Vector3 pos = targetAtom.position + Vector3.up * 1;
                camtarget.position = pos;
                camtarget.LookAt(targetAtom, Vector3.up);
                SuperController.singleton.centerCameraTarget.targetCamera.transform.LookAt(targetAtom, Vector3.up);
            }
            else if (Input.GetKeyDown(KeyCode.Keypad6))
            {
                Vector3 pos = targetAtom.position + targetAtom.right * 1;
                camtarget.position = pos;
                camtarget.LookAt(targetAtom, Vector3.up);
                SuperController.singleton.centerCameraTarget.targetCamera.transform.LookAt(targetAtom, Vector3.up);
            }
            else if (Input.GetKeyDown(KeyCode.Keypad2))
            {
                Vector3 pos = targetAtom.position + Vector3.forward * 1;
                camtarget.position = pos;
                camtarget.LookAt(targetAtom, Vector3.up);
                SuperController.singleton.centerCameraTarget.targetCamera.transform.LookAt(targetAtom, Vector3.up);
            }
            else if (Input.GetKeyDown(KeyCode.Keypad8))
            {
                Vector3 pos = targetAtom.position - Vector3.forward * 1;
                camtarget.position = pos;
                camtarget.LookAt(targetAtom, Vector3.up);
                SuperController.singleton.centerCameraTarget.targetCamera.transform.LookAt(targetAtom, Vector3.up);
            }
        }  
    }

    private void ShowTexturePicker()
    {
        SuperController.LogMessage(GetPluginPath());
        var defaultPaths = new List<string> {
                $"{GetPluginPath()}Textures",
                $"{GetPluginPath()}Custom/Atom/InvisibleLight/Textures",
                $"Custom/Assets/MyAssets"
            };

        var shortcuts = FileManagerSecure.GetShortCutsForDirectory(
            "Custom/Atom/Assets/MyAssets",
            allowNavigationAboveRegularDirectories: true,
            useFullPaths: true,
            generateAllFlattenedShortcut: true,
            includeRegularDirsInFlattenedShortcut: true
        );

        SuperController.singleton.GetMediaPathDialog(
            (p) => {
                try
                {
                    SuperController.LogMessage(p);
                }
                catch (Exception e)
                {
                    SuperController.LogError(e.ToString());
                }
            },
            filter: "png|jpg|gif",
            suggestedFolder: defaultPaths.FirstOrDefault(p => FileManagerSecure.DirectoryExists(p)),
            shortCuts: shortcuts,
            showInstallFolderInDirectoryList: true
        );
    }

    public string GetPluginPath()
    {
        string id = name.Substring(0, name.IndexOf('_'));
        string filename = manager.GetJSON()["plugins"][id].Value;
        string path = filename.Substring(0, filename.LastIndexOfAny(new char[] { '/', '\\' }) + 1);
        return FileManagerSecure.NormalizePath(path);
    }

    private void OnDestroy()
    {
        Utils.OnDestroyUI();
    }
}
